#include "../../include/mysql/CMySqlOp.h"

CMySQLOper::CMySQLOper()
    :pMysqlOp(NULL)
    ,dbHost("")
    ,dbPort(0)
    ,dbUser("")
    ,dbPwd("")
    ,dbSchema("")
    ,errMsg("")
{

}

CMySQLOper::~CMySQLOper()
{
    if(pMysqlOp != NULL)
        mysql_close(pMysqlOp);
}

//测试数据库连接
bool CMySQLOper::TestMysql(std::string &db_host, unsigned int db_port, std::string &db_user,
        std::string &db_pwd, std::string db_schema,std::string &err)
{
    MYSQL mysqlTest;

    //初始化
    mysql_init(&mysqlTest);  

    //设置属性
    mysql_options(&mysqlTest,MYSQL_READ_DEFAULT_GROUP,"Processor");

    //连接数据库
    if(!mysql_real_connect(&mysqlTest,db_host.c_str(),db_user.c_str(),db_pwd.c_str()
            ,db_schema.c_str(),db_port,NULL,0))
    {
        char temp[128] = {0x00};
        sprintf(temp,"数据库连接失败，错误码[%d]，详情:%s",
           mysql_errno(&mysqlTest),mysql_error(&mysqlTest));
        err = temp;
        mysql_close(&mysqlTest);
        return false;
    }

   
    //获取数据库信息
    //关闭连接
    mysql_close(&mysqlTest);

    return true;
}

//连接数据库
bool CMySQLOper::Connect(std::string &db_host, unsigned int db_port, std::string &db_user,
        std::string &db_pwd, std::string db_schema)
{
    if(pMysqlOp != NULL)
        mysql_close(pMysqlOp);

    pMysqlOp = mysql_init(NULL);

    //设置断线自动重连（默认关闭）
    bool reConnect = true;
    if(mysql_options(pMysqlOp,MYSQL_OPT_RECONNECT,&reConnect))
    {
        char temp[128] = {0x00};
        sprintf(temp,"设置断线自动重连失败，错误码[%d]，详情:%s",
           mysql_errno(pMysqlOp),mysql_error(pMysqlOp));
        errMsg = temp;
        mysql_close(pMysqlOp);
        return false;
    }

    //连接数据库
    if(NULL == mysql_real_connect(pMysqlOp,db_host.c_str(),db_user.c_str(),db_pwd.c_str(),
        db_schema.c_str(),db_port, NULL,0))
    {
        char temp[128] = {0x00};
        sprintf(temp,"数据库连接失败，错误码[%d]，详情:%s",
           mysql_errno(pMysqlOp),mysql_error(pMysqlOp));
        errMsg = temp;
        mysql_close(pMysqlOp);
        return false;
    }

    //设置连接字符集

    dbHost = db_host;
    dbUser = db_user;
    dbPwd = db_pwd;
    dbPort = db_port;
    dbSchema = db_schema;

    return true;
}

void CMySQLOper::CloseConnect(void)
{
    mysql_close(pMysqlOp);
}

 //增
int CMySQLOper::Add()
{
    return -1;
}

//删
bool CMySQLOper::Delete()
{
    return true;
}

//改
bool CMySQLOper::Alter()
{
    return true;
}

//查
MYSQL_RES* CMySQLOper::select(std::string query)
{
    //检查连接是否存在
    if(mysql_ping(pMysqlOp))
    {
        errMsg = "数据库连接失效";
        mysql_close(pMysqlOp);
        return NULL;
    }
    
    //查询数据
    if(mysql_query(pMysqlOp,query.c_str()))
    {
        int err_no = mysql_errno(pMysqlOp);
        char temp[128] = {0x00};
        sprintf(temp,"SQL语句执行失败，错误码[%d]",err_no);
        errMsg = temp;
        return NULL;
    }

    //return mysql_store_result(pMysqlOp);
    return mysql_use_result(pMysqlOp);
}
